package com.fkdx.service;

import com.fkdx.common.enums.DigiEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 解析digi
 *
 * @author wsh
 * @date 2025-01-02 19:56
 **/
@Slf4j
@Service()
public class DigiService {
  private RestTemplate restTemplate = new RestTemplate(httpRequestFactory());
  private String hurl = "https://user.digi-co.net";

  public ClientHttpRequestFactory httpRequestFactory() {
    return new HttpComponentsClientHttpRequestFactory(httpClient());
  }

  public HttpClient httpClient() {
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
      .register("http", PlainConnectionSocketFactory.getSocketFactory())
      .register("https", SSLConnectionSocketFactory.getSocketFactory())
      .build();
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    connectionManager.setMaxTotal(100);
    connectionManager.setDefaultMaxPerRoute(10);
    connectionManager.setValidateAfterInactivity(100);

    RequestConfig requestConfig = RequestConfig.custom()
      .setSocketTimeout(6000)
      .setConnectTimeout(6000)
      .setConnectionRequestTimeout(6000)
      .build();

    // 设置报文信息headers
    List<Header> headers = new ArrayList<>();
    headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"));
    headers.add(new BasicHeader("Accept-Encoding", "gzip, deflate, br, zstd"));
    headers.add(new BasicHeader("Accept-Language", "zh-CN,zh;q=0.9"));
    //headers.add(new BasicHeader("Connection", "Keep-Alive"));
    //headers.add(new BasicHeader("Content-type", "application/json"));

    headers.add(new BasicHeader("Sec-Fetch-Site", "same-origin"));
    headers.add(new BasicHeader("Sec-Fetch-Mode", "cors"));
    headers.add(new BasicHeader("Sec-Fetch-Dest", "empty"));
    headers.add(new BasicHeader("Sec-Ch-Ua-Platform", "\"Windows\""));
    headers.add(new BasicHeader("Sec-Ch-Ua-Mobile", "?0"));
    headers.add(new BasicHeader("Sec-Ch-Ua", "\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\""));
    //headers.add(new BasicHeader("Origin", "https://g4b.giftee.biz"));

    return HttpClientBuilder.create()
      .setDefaultRequestConfig(requestConfig)
      .setConnectionManager(connectionManager)
      .setDefaultHeaders(headers)
      .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
      .setRetryHandler(new DefaultHttpRequestRetryHandler(2, true))
      .build();
  }

  public String[] getBalance(String burl, String cookiesStr) {
    String response = postCookie(burl, cookiesStr);
    String[] str = response.split("class=\"c_point header-point\">");
    String[] code = str[1].split("</span>");
    String[] _tokenStr =response.split("_token]\" value=\"");
    String[] _token = _tokenStr[1].split("\" />");
    String[] res = new String[2];
    res[0] = code[0].replace(",", "");
    res[1] = _token[0];
    return res;
  }
  private String postCookie(String url, String cookiesStr) {
    log.info("浏览器缓存{}", cookiesStr);
    // 创建一个Cookie拦截器
    ClientHttpRequestInterceptor cookieInterceptor = new ClientHttpRequestInterceptor() {
      @Override
      public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException, IOException {
        HttpHeaders headers = request.getHeaders();
        List<String> cookies = headers.get("Cookie");
        if (cookies == null) {
          String[] ss = cookiesStr.split(";");
          for (String cookie : ss) {
            log.info("赋值{}", cookie);
            headers.add("Cookie", cookie);
          }

          //headers.add("Cookie", "anotherCookie=abcdef"); // 可以添加多个cookie
        } else {
          // 如果已经有Cookie，则添加新的Cookie
          String cookie = "PHPSESSID_GIFPY_WEB=9dj0r1ujtr9r656s4f6c9hpu1j";
          cookies.add(cookie);
        }
        return execution.execute(request, body);
      }
    };
    // 注册拦截器
    restTemplate.getInterceptors().add(cookieInterceptor);
    // 发送请求，此时会携带Cookie
    String response = restTemplate.getForObject(hurl.concat(url), String.class);
    log.info(response);
    return response;
  }

  public String getExchange(String jurl, String cookiesStr, String token, String amt, DigiEnum d) {
    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();		// 不能使用HashMap，源码中会讲！
    map.add(d.getHead() + "worth]", amt);
    if (d.equals(DigiEnum.APPLE)) {
      if (amt.equals("160")) {
        map.add(d.getHead() + "giftType]", "629791");
      } else if (amt.equals("500")) {
        map.add(d.getHead() + "giftType]", "499809");
      } else if (amt.equals("1000")) {
        map.add(d.getHead() + "giftType]", "499810");
      } else if (amt.equals("2000")) {
        map.add(d.getHead() + "giftType]", "499811");
      } else if (amt.equals("3000")) {
        map.add(d.getHead() + "giftType]", "499902");
      } else if (amt.equals("5000")) {
        map.add(d.getHead() + "giftType]", "499903");
      } else if (amt.equals("10000")) {
        map.add(d.getHead() + "giftType]", "499904");
      } else  {
        throw new RuntimeException("金额不符合");
      }
      map.add(d.getHead() + "worth]", amt);

    } else if(d.equals(DigiEnum.GOOGLE)) {
      if (Integer.parseInt(amt) < 100 || Integer.parseInt(amt) > 30000) {
        throw new RuntimeException("金额不符合");
      }
    }
    map.add(d.getHead() + "giftCategory]", d.getType());
    map.add(d.getHead() + "_token]", token);
    String response = getCode(jurl, cookiesStr, map);
    String[] jg = response.split("Redirecting to ");
    String[] jg1 = jg[1].split("</title>");
    return jg1[0].trim();
  }

  public String getCode(String url, String cookiesStr,MultiValueMap<String, String> map) {
    log.info("浏览器缓存{}", cookiesStr);
    // 创建一个Cookie拦截器
    ClientHttpRequestInterceptor cookieInterceptor = new ClientHttpRequestInterceptor() {
      @Override
      public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException, IOException {
        HttpHeaders headers = request.getHeaders();
        List<String> cookies = headers.get("Cookie");
        if (cookies == null) {
          String[] ss = cookiesStr.split(";");
          for (String cookie : ss) {
            headers.add("Cookie", cookie);
          }

          //headers.add("Cookie", "anotherCookie=abcdef"); // 可以添加多个cookie
        } else {
          // 如果已经有Cookie，则添加新的Cookie
          String cookie = "PHPSESSID_GIFPY_WEB=9dj0r1ujtr9r656s4f6c9hpu1j";
          cookies.add(cookie);
        }
        return execution.execute(request, body);
      }
    };
    // 注册拦截器
    restTemplate.getInterceptors().add(cookieInterceptor);
    // 发送请求，此时会携带Cookie
    // 请求体
    String response = restTemplate.postForObject(hurl.concat(url),map, String.class);
    log.info(response);
    return response;
  }

  public String getResult(String rurl, String c, String type) {
    while (true) {
      String response = postCookie(rurl, c);
      String[] str = response.split("data-clipboard-text=\"");
      if (str.length > 1) {
        String[] jg = str[1].split("\">");
        return jg[0];
      }
      try {
        Thread.sleep(5000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }



  }
}
